package vworld.dao.world;

import generated.domain.room.Room;
import generated.domain.world.World;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import vworld.dao.HibernateUtil;

public class WorldDAO {

	public void createWorld(World pWorld) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.save(pWorld);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void deleteWorld(World pWorld) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.delete(pWorld);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public void saveOrUpdateWorld(World pWorld) {
		Transaction tx = null;
		Session session = HibernateUtil.currentSession();
		try {
			tx = session.beginTransaction();
			session.saveOrUpdate(pWorld);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public World getWorld(String pName) {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session
					.createQuery("from World w where w.name = :name");
			query.setString("name", pName);

			for (Object obj : query.list()) {
				return (World) obj;
			}
			return null;
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public World[] getWorlds() {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session.createQuery("from World");

			query.list();

			World[] worlds = new World[query.list().size()];
			int i = 0;
			for (Object obj : query.list()) {
				World world = (World) obj;
				worlds[i] = world;
				i++;
			}
			return (worlds);
		} finally {
			HibernateUtil.closeSession();
		}
	}

	public World getWorldByRoomName(String roomName) {
		try {
			Session session = HibernateUtil.currentSession();
			Query query = session.createQuery("from World w");

			for (Object obj : query.list()) {
				World w = (World) obj;
				Room[] rooms = w.getRooms();
				for (Room r : rooms) {
					if (r.getName().equalsIgnoreCase(roomName)) {
						return w;
					}
				}
			}
			return null;
		} finally {
			HibernateUtil.closeSession();
		}
	}
}
